<?php
namespace plugins\logistics\controller;

use cmf\controller\PluginAdminBaseController;
use think\Db;
use think\db\Query;
use plugins\logistics\model\LogisticsKdniaoModel;
use plugins\store\Common;
use think\Request;
/**
 * 
 */
class LogisticsKdniaoController extends PluginAdminBaseController
{
    private  $com = '';
    private  $KdApi = '';
    private  $OrderCode;

    protected function _initialize()
    {
        parent::_initialize();
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        }
        $this->com = new Common;
        $this->KdApi = new LogisticsKdniaoModel;
        
    }
    
    /**
     * 查询快递单号
     */
    public function index(){
        $param = $this->request->param();
        
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        //读取配置
        $EXinfo = db('logistics_confign')->where('store_id',$allow)->find();

        if (isset($param['ShipperCode']) && !empty($param['ShipperCode'])) {

            $orderInfo['ShipperCode']=$param['ShipperCode'];
            $orderInfo['LogisticCode']=$param['LogisticCode'];
            $orderInfo['CustomerName']=$param['CustomerName'];
            $orderInfo['OrderCode']=empty($param['OrderCode'])?'':intval($param['OrderCode']);
            //判断改物流是否已完成
            //判断数据库该物流是否是在2小时内的查询记录
            
            $where = ['ShipperCode'=>$orderInfo['ShipperCode'],'LogisticCode'=>$orderInfo['LogisticCode']];
            $logistics = db('logistics_record')->where($where)->find();

            
             //判断是否有记录
            if($logistics){//有记录
           
            $time = intval( (time()-$logistics['add_time'] )/3600);//相差时间


            if($logistics['State']==3 || $time<2){//物流已签收或两小时内更新过
                $msg = json_decode($logistics['logistics'],true);
            }else{
                //获取物流信息
                $data = $this->KdApi->getOrderTracesByJson($orderInfo['ShipperCode'],$orderInfo["LogisticCode"],$EXinfo,$orderInfo['CustomerName']);
                $msg = json_decode($data,true);
                if($msg['Success']==true){
                    db('logistics_record')->where($where)->update(['logistics'=>$data,'State'=>$msg['State']]);//更新物流信息
                }
            }      

            }else{
                //获取物流信息
                $data = $this->KdApi->getOrderTracesByJson($orderInfo['ShipperCode'],$orderInfo["LogisticCode"],$EXinfo,$orderInfo['CustomerName']);
                $msg = json_decode($data,true);
                if($msg['Success']==true){
                    $time = time();
                    db('logistics_record')->insert(['ShipperCode'=>$orderInfo['ShipperCode'],'LogisticCode'=>$orderInfo['LogisticCode'],'logistics'=>$data,'add_time'=>$time,'State'=>$msg['State']]);//保存物流信息                       
                }
               
            } 

            if($msg['Success']==true){
                
            $code = Db::name('logistics')->where('code',$msg['ShipperCode'])->find();
            $msg['company']=$code['company'];

            //按照时间排序
            if ($msg['State'] != 0) {
                $ctime_str = array();
                foreach($msg['Traces'] as $key=>$v){
                    $msg['Traces'][$key]['AcceptTime'] = strtotime($v['AcceptTime']);
                    $ctime_str[] = $msg['Traces'][$key]['AcceptTime'];
                }
                array_multisort($ctime_str,SORT_DESC,$msg['Traces']);
                foreach ($msg['Traces'] as $key => $value) {
                    $value['AcceptTime'] = date('Y-m-d H:i:s',$value['AcceptTime']);
                    $msg['Traces'][$key] = $value;
                }
            }
            /* 
            物 流 状 态 ：
            0-无 轨 迹
            1-已揽收
            2-在途中
            3-签收 */
            if($msg['State']=='0'){
                $msg['State']='无轨迹';
            }else if($msg['State']=='1'){
                $msg['State']='已揽收';
            }else if($msg['State']=='2'){
                $msg['State']='在途中';
            }else if($msg['State']=='3'){
                $msg['State']='签收';
            }

            }
            
        }
        $info = Db::name('logistics')->select();

        $this->assign('info',$info);
        $this->assign('msg',isset($msg)?$msg:false);
        return $this->fetch();
    }



    /**
     * 快递鸟配置
     */
    public function configpage()
    {
        $param = $this->request->param();
        //用户权限判断
        $allow = $this->com->getAllowAccess();
        if($allow =='true')$allow ='admin';
        $EXinfo = db('logistics_confign')->where('store_id',$allow)->find();
        if (isset($param['edit'])) {
            
            $edit = $param['edit'];
            $edit['store_id']=$allow;
            $edit['config']=json_encode($param['config']);

            
            if($EXinfo){
                $res = db('logistics_confign')->update($edit);  
            }else{
                $res = db('logistics_confign')->insert($edit); 
            } 
            if($res)return api_json_echo(true,'保存成功','',200);
            
        }

        
        if(!$EXinfo) $EXinfo = ['EBusinessID'=>'','AppKey'=>'','printName'=>'','config'=>'','PayType'=>'','code'=>''];

        $this->assign('EXinfo',$EXinfo);
        $this->assign('config', json_decode($EXinfo['config'],true) );

        return $this->fetch();
    }

    


    /**
     * 电子面单
     * @param   $ShipperCode 快递公司代码
     * @param   $OrderCode 订单编号
     * @param   $GoodsName 商品名称
     * @param  array $sender 寄件人  ["Name"=>"寄件人","Mobile"=>"电话","ProvinceName"=>"省","CityName"=>"市","ExpAreaName"=>"区","Address"=>"详细地址"]
     * @param  array $receiver 提交的数据收件人  ["Name"=>"收件人","Mobile"=>"电话","ProvinceName"=>"省","CityName"=>"市","ExpAreaName"=>"区","Address"=>"详细地址"]
     * @return url响应返回的html
     */
    public function placeOrder($ShipperCode='',$OrderCode='',$sender='',$receiver='',$GoodsName="其他")
    {
        $param = $this->request->param();
        if(!empty($param['OrderCode'])){
            $ShipperCode=$param['ShipperCode'];
            $OrderCode=$param['OrderCode'];
            $sender=$param['sender'];
            $receiver=$param['receiver'];
        }
        $KdApi = new LogisticsKdniaoModel;
        $com = new Common;

        //用户权限判断
        $allow = $com->getAllowAccess();
        if($allow == true)$allow='admin'; 
        //读取配置
        $EXinfo = db('logistics_confign')->where('store_id',$allow)->find();
        if(!$EXinfo) return api_json_echo(false,'快递鸟插件未配置','',100);
        $config = json_decode($EXinfo['config'],true);
        
        //构造电子面单提交信息
        $eorder = [];
        $eorder["ShipperCode"] = $ShipperCode;//快递公司编码
        $eorder["OrderCode"] = $OrderCode;//订单编号(自定义，不可重复)
        $eorder["PayType"] = $EXinfo['PayType'];//邮费支付方式:1-现付，2-到付，3-月结，4-第三方支付(仅SF支持)
        $eorder["ExpType"] = 1;//快递类型：1-标准快件
        // $eorder["IsReturnPrintTemplate"]=1;//返回面单

        
        if(empty($config[$ShipperCode])) return api_json_echo(false,'快递鸟不支持该物流','',100);
        $eorder = array_merge($eorder,$config["$ShipperCode"]);


        $commodityOne = [];
        $commodityOne["GoodsName"] = $GoodsName;//商品名称
        $commodity = [];
        $commodity[] = $commodityOne;

        $eorder["Sender"] = $sender;
        $eorder["Receiver"] = $receiver;
        $eorder["Commodity"] = $commodity;

        
        //调用电子面单
        $jsonParam = json_encode($eorder, JSON_UNESCAPED_UNICODE);
        $res = $KdApi->submitEOrder($jsonParam,$EXinfo);
        $res = json_decode($res,true);

        
        if($res['Success']==true)
        {
            $info = ['OrderCode'=>$res['Order']['OrderCode'],'ShipperCode'=>$res['Order']['ShipperCode'],'LogisticCode'=>$res['Order']['LogisticCode'],'PrintTemplate'=>$res['PrintTemplate']];
            return api_json_echo(false,$res['Reason'],$info,200);
        }else{

        return api_json_echo(false,$res['Reason'],$ShipperCode,100);
        }
    }


    /**
     * 打印
     * @param  array $OrderCode 订单编号  ['order_5f2cf0334f64d','order_5f2cf0334f64e']
     * @return url响应返回的html
     */
    public function order_print($OrderCode=[])
    {       
        $KdApi = new LogisticsKdniaoModel;
        $com = new Common;
        $param = $this->request->param();
        if(!empty($param['OrderCode'])){
            $OrderCode=$param['OrderCode'];
        }
        //用户权限判断
        $allow = $com->getAllowAccess();
        if($allow == true)$allow='admin'; 
        //读取配置
        $EXinfo = db('logistics_confign')->where('store_id',$allow)->find();
        if(!$EXinfo) return api_json_echo(false,'快递鸟插件未配置','',100);
       
        
        //打印机名称打散
        $printName = explode(",",$EXinfo['printName']);
        $i=0;
        foreach( $OrderCode as $key =>$value)
        {
            $request_data[$key] = ['OrderCode'=>$value,'PortName'=>$printName[$i]];
            $i++;
            if($i==count($printName))$i=0;
        }
        
        //打印面单
        $request_data = json_encode($request_data, JSON_UNESCAPED_UNICODE);

        $Print =  $KdApi->build_form($request_data,$EXinfo); 

        if($Print['Complete'] == "Failed") return api_json_echo(false,'失败','',100); 
        // return api_json_echo(false,'失败','',100);
    }



}
